<template>
  <el-dialog
    top="30px"
    width="800px"
    class="dialog-sm"
    append-to-body
    title="保费核算"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <base-view :edit-row="editRow"></base-view>
    <div class="d-flex">
      <div class="mr-5">
        <div style="width: 80px"></div>
      </div>
      <table class="table table-sm table-borderless accounting-table">
        <colgroup>
          <col width="15%" />
          <col width="35%" />
          <col width="15%" />
          <col width="35%" />
        </colgroup>
        <tbody>
          <tr>
            <td colspan="4">
              <div class="text-muted pt-3 pb-2" style="font-size: 1.2rem">核算内容：</div>
            </td>
          </tr>
          <tr>
            <td>担保费率：</td>
            <td>
              <span v-if="isViewMode">{{ editRow.gua_rate || '-' }}%</span>
              <el-input
                size="small"
                v-model="guaRate"
                v-input-number="{ min: 0, max: 100, fixed: 2 }"
                v-else
              >
                <template slot="append">%</template>
              </el-input>
            </td>
            <td>应缴时间：</td>
            <td>{{ $utils.dateFormat(editRow.due_warrant_date, 'yyyy年MM月dd日') || '-' }}</td>
          </tr>
          <tr>
            <td>在保余额：</td>
            <td>
              <span v-if="!hasWarrantRate" class="text-muted">暂无担保费率</span>
              <span v-else-if="isViewMode">{{ editRow.left_funds }} 万元</span>
              <div v-else class="d-flex justify-content-between align-items-center">
                <div>{{ leftFunds }} {{ leftFunds ? '万元' : '-' }}</div>
                <el-button
                  v-if="!isFinanceUser"
                  slot="append"
                  size="small"
                  type="primary"
                  plain
                  @click="onEditRepay"
                  :disabled="loading"
                >
                  修改保额
                </el-button>
              </div>
            </td>
            <td>缴费金额：</td>
            <td>{{ dueWarrantFee || '-' }}万元</td>
          </tr>
          <tr>
            <td></td>
            <td colspan="3" class="pt-5">
              <div v-if="!isViewMode">
                <div class="mb-1">
                  <el-button
                    v-if="!isFinanceUser"
                    type="primary"
                    @click="handleAbConfirm"
                    :disabled="!hasWarrantRate || saveLoading"
                    :loading="saveLoading"
                    class="btn-long"
                  >
                    应缴费核算
                  </el-button>

                  <el-button
                    v-else
                    type="primary"
                    @click="handleFinanceConfirm"
                    :disabled="!hasWarrantRate || saveLoading"
                    :loading="saveLoading"
                    class="btn-long"
                  >
                    应缴费确认
                  </el-button>

                  <el-button class="btn-long" @click="beforeClose">取消</el-button>
                </div>
                <el-alert
                  v-if="!hasWarrantRate"
                  title="无担保费率"
                  type="warning"
                  show-icon
                  :closable="false"
                  style="width: 210px"
                ></el-alert>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <repay-dialog
      :visible.sync="repayVisible"
      :query-id="editRow.customer_related_id"
      @success="handleRepaySuccess()"
    ></repay-dialog>
  </el-dialog>
</template>

<script>
// 项目经理核算操作
import { mapGetters } from 'vuex'
import { mul } from '@vimi/utils-tool'
import { num } from '@/common/plugins/tools/format'
import { CheckStatus } from '@/bigcredit/views/settle/accounting/model'

import BaseView from '@/bigcredit/views/settle/accounting/components/BaseView'
import RepayDialog from '@/credit/views/city/self/after/repay/RepayDialog'

export default {
  components: {
    BaseView,
    RepayDialog,
  },
  props: {
    visible: Boolean,
    editRow: {
      type: Object,
      default() {
        return {}
      },
    },
    viewMode: Boolean,
  },
  data() {
    return {
      saveLoading: false,
      leftFunds: '',
      guaRate: '',
      loadYear: 1,

      loading: false,
      repayVisible: false,
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user', 'userId']),
    isFinanceUser() {
      return this.user.scopeArr.includes('financeO')
    },

    isViewMode() {
      return this.viewMode
    },
    hasWarrantRate() {
      return !!this.guaRate
    },
    warrantRate() {
      return +this.guaRate || 0
    },

    // 是否为一次性收取保费
    isDisposable() {
      return num(this.editRow.gua_fee_coll_type) === 1
    },
    checkStatus() {
      return num(this.editRow.check_status)
    },

    dueWarrantFee() {
      const funds = +this.leftFunds || 0
      // 按万元为单位，保留4位小数，四舍五入 @唐文峰_20221130
      return Math.round(this.warrantRate * funds * 100) / 1e4
    },

    // 总共核算金额：
    // 按年收取: = 缴费金额
    // 一次性收取: = 缴费金额 * 贷款年限
    totalWarrantFee() {
      return mul(this.dueWarrantFee, this.isDisposable ? this.loadYear : 1)
    },
  },
  watch: {
    editRow: {
      handler: function () {
        this.initForm()
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    beforeClose() {
      this.$emit('update:visible', false)
    },
    async initForm() {
      this.guaRate = this.editRow.gua_rate || ''
      this.leftFunds = this.editRow.left_funds || ''

      if (this.checkStatus !== CheckStatus.Finished) {
        // 一次性收取担保费，需要贷款年限来计算总担保费
        const related = await this.getRelatedData()
        this.loadYear = num(Math.ceil((related.months || 0) / 12), 1)

        if (!this.leftFunds) {
          this.leftFunds = related.left_funds
        }
      }
    },
    getRelatedData() {
      this.loading = true
      return this.$api
        .getData({
          table: 'customer_related',
          params: {
            'customer_related_id.eq': this.editRow.customer_related_id,
            fields: ['left_funds', 'months'],
          },
        })
        .then(res => {
          return (res.data || [])[0] || {}
        })
        .finally(() => {
          this.loading = false
        })
    },
    onEditRepay() {
      this.repayVisible = true
    },

    // 还款登记完成后，更新在保余额
    async handleRepaySuccess() {
      const related = await this.getRelatedData()
      this.leftFunds = related.left_funds
    },

    // AB角核算
    handleAbConfirm() {
      if (!this.leftFunds) {
        this.$message.error('没有在保余额')
        return false
      }

      this.$confirm('确认核算保费?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      })
        .then(() => {
          const formData = {
            gua_rate: this.guaRate,
            left_funds: this.leftFunds,
            check_status: 1,
            // due_warrant_date: this.$utils.dateFormat(new Date()),
            due_warrant_fee: this.dueWarrantFee,
            actual_warrant_fee: this.totalWarrantFee,
          }
          this.updateData(formData)
            .then(() => {
              this.$message.success(`保费核算成功`)
              this.$emit('success')
              this.beforeClose()
            })
            .catch(() => {
              this.$message.error(`保费核算失败，请重试`)
            })
        })
        .catch(() => {})
    },

    // 账务人员确认核算
    handleFinanceConfirm() {
      this.$confirm('确认保费核算?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      })
        .then(() => {
          const formData = {
            gua_rate: this.guaRate,
            // left_funds: this.leftFunds,
            check_status: 2,
            // due_warrant_date: this.$utils.dateFormat(new Date()),
            due_warrant_fee: this.dueWarrantFee,
            actual_warrant_fee: this.totalWarrantFee,
          }
          this.updateData(formData)
            .then(() => {
              this.$message.success(`保费核算确认成功`)
              this.$emit('success')
              this.beforeClose()
            })
            .catch(err => {
              this.$message.error(err?.data?.error_description || '保费核算确认失败，请重试')
            })
        })
        .catch(() => {})
    },

    updateData(data) {
      this.saveLoading = true
      return this.$api
        .updateData({
          table: 'credit_warrant_fee_record',
          id: this.editRow.id,
          data,
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
  },
}
</script>
<style lang="scss" scoped>
.accounting-progress {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 3px solid;
  padding-top: 15px;
  text-align: center;
  clip-path: polygon(0% 90%, 0% 0%, 100% 0%, 100% 90%);
}
.label-text {
  display: inline-block;
  min-width: 90px;
  color: gray;
}
.accounting-table {
  width: auto;
  flex: 1;
  > tbody tr td:nth-of-type(2n + 1) {
    color: gray;
  }
}
</style>
